import type { Directive } from 'vue'

const imgLazy: Directive = {
  mounted(el: HTMLImageElement, binding, vnode, prevVnode) {
    let imgUrl = binding.value

    if (el.getBoundingClientRect().bottom - el.clientHeight <= window.innerHeight) {
      el.src = imgUrl
      return
    }

    const handleScroll = () => {
      if (el.getBoundingClientRect().bottom - el.clientHeight <= window.innerHeight) {
        el.src = imgUrl
        window.removeEventListener('scroll', handleScroll)
      }
    }

    window.addEventListener('scroll', handleScroll)
  }
}

export default imgLazy
